/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ie.tcd.cs.railtickets.server.net;

import java.io.IOException;
import java.net.ServerSocket;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ie.tcd.cs.railtickets.commons.util.PropertiesUtil;
import java.net.Socket;
import java.util.Properties;

/**
 *
 * @author Wenbo Sun
 */
public class ServerOperator {

    private ServerSocket serverSocket;
    private static final Log log = LogFactory.getLog(ServerOperator.class);
    private static String configFile = "config/server.properties";
    private static Properties serverConfig;

    public ServerOperator() {
        try {
            if (serverConfig == null)
                loadConfig();
            int port = Integer.parseInt(PropertiesUtil.getProperties(configFile).getProperty("port"));
            serverSocket = new ServerSocket(port);
//            serverSocket = new ServerSocket(9999);
        } catch (IOException ex) {
            log.error("create server socket failed", ex);
        }
    }

    public void excute() {
        while(true) {
            try {
                log.info("accepting data from agent ...");
                Socket socket = serverSocket.accept();

                //handle the requests in threads
                OperationHandler handler = new OperationHandler(socket);
                log.debug("create a thread for processing request ...");
                handler.start();
//                handler.run();
            } catch (IOException ex) {
                log.error("server socket accept errors", ex);
            }
        }
    }

    public static void loadConfig() {
        try {
            serverConfig = PropertiesUtil.getProperties(configFile);
//            serverConfig = PropertiesUtil.getProperties(ClassLoader.getSystemClassLoader().getResource(configFile).getFile());
        } catch (IOException ex) {
            log.error("load configuration failed", ex);
        }
    }

    public static Properties getProperties() {
        if (serverConfig == null)
                loadConfig();
        return serverConfig;
    }

}
